package org.force4spring.query;

import java.util.ArrayList;
import java.util.List;

public class LogicalExpression implements Expression {
	private List<Expression> expressions;
	private String operator;
	
	protected LogicalExpression(String operator) {
		this.operator = operator;
		expressions = new ArrayList<Expression>();
	}
	
	public static LogicalExpression or() {
		return new LogicalExpression(Operator.OR);
	}
	
	public static LogicalExpression and() {
		return new LogicalExpression(Operator.AND);
	}
	
	/**
	 * @see org.force4spring.query.Expression#buildSOQL()
	 */
	public String buildSOQL() {
		StringBuffer soql = new StringBuffer();
		if (expressions.size() > 0) {
			soql.append("(");
		}
		for (int i=0;i<expressions.size();i++) {
			if (i > 0) {
				soql.append(" ").append(operator).append(" ");
			}
			soql.append(expressions.get(i).buildSOQL());
		}
		if (expressions.size() > 0) {
			soql.append(")");
		}
		return soql.toString();
	}
	
	public LogicalExpression add(Expression expr) {
		expressions.add(expr);
		return this;
	}

	public interface Operator {
		public static final String OR = "OR";
		public static final String AND = "AND";
	}
}
